package com.feidian.helper.ui.fragment;

/**
 * 
 * @author WangCheng
 * @category
 * @category 懒人帮求帖界面
 * @category 内嵌XListView自定义组件
 */

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONObject;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.feidian.helper.R;
import com.feidian.helper.adapter.XListViewAdapter;
import com.feidian.helper.bean.Item;
import com.feidian.helper.bean.Table;
import com.feidian.helper.net.NetManager;
import com.feidian.helper.ui.AddNewsActivity;
import com.feidian.helper.ui.NewsDetailsActivity;
import com.feidian.helper.ui.view.XListView;
import com.feidian.helper.ui.view.OnRefreshListener;
import com.feidian.helper.util.Utils;
import com.google.gson.JsonObject;
import com.handmark.pulltorefresh.library.PullToRefreshBase.Mode;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;

@SuppressLint("NewApi")
public class MessageFragment extends Fragment {
	private final int REFRESH = 0x123;
	private final int LOAD = 0x124;
	private PullToRefreshListView mRefreshListView = null;
	private XListViewAdapter adapter;
	private TextView mTitle = null;
	private ImageView mAddNews;
	// private boolean isRefreshing = false;
	// private boolean isLoading = false;
	private static int page = 1;
	public static List<Item> itemList = new ArrayList<Item>();
	public static int pos;

	

	private Handler mHandler = new Handler() {
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case REFRESH:
				page = 2;
				if (itemList != null && (String) msg.obj != null)
					addItems(itemList, (String) msg.obj, 0);
				adapter.notifyDataSetChanged();
				mRefreshListView.onRefreshComplete();
				mRefreshListView.setEnabled(true);
				break;
			case LOAD:
				page++;
				if (itemList != null && (String) msg.obj != null) {
					addItems(itemList, (String) msg.obj, 1);
				}
				adapter.notifyDataSetChanged();
				mRefreshListView.onRefreshComplete();
				mRefreshListView.setEnabled(true);
				break;
			}
		}
	};

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		View v = inflater.inflate(R.layout.listview_swipe, container, false);
		mTitle = (TextView) v.findViewById(R.id.tv_top_title);
		mTitle.setText(getActivity().getResources().getString(R.string.main));
		mRefreshListView = (PullToRefreshListView) v
				.findViewById(R.id.list_swipe);
		adapter = new XListViewAdapter(getActivity(), itemList);
		mRefreshListView.setMode(Mode.BOTH);
		
		mRefreshListView
				.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2() {

					@Override
					public void onPullDownToRefresh(
							PullToRefreshBase refreshView) {
						// TODO Auto-generated method stub
						onDownPullRefresh();
					}

					@Override
					public void onPullUpToRefresh(PullToRefreshBase refreshView) {
						// TODO Auto-generated method stub
						onLoadingMore();
					}
				});
		mRefreshListView.setAdapter(adapter);

		mRefreshListView.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {

				pos = position - 1;
				getActivity().startActivity(
						new Intent(getActivity(), NewsDetailsActivity.class));
			}

		});

		mAddNews = (ImageView) v.findViewById(R.id.add_msg);
		mAddNews.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				startActivity(new Intent(getActivity(), AddNewsActivity.class));
			}
		});
		onDownPullRefresh();
		return v;
	}

	public void onDownPullRefresh() {
		itemList.clear();
		Log.e("onRefresh", "onRefresh");
		String url = "http://115.29.103.105/User/getRefreshDate";
		List<NameValuePair> params = new ArrayList<NameValuePair>();
		params.add(new BasicNameValuePair(Table.state, "1"));
		params.add(new BasicNameValuePair(Table.page, "1"));
		RefreshThread refreshThread = new RefreshThread(url, params);
		refreshThread.start();
		/*
		 * Message msg = new Message(); msg.what = REFRESH;
		 * mHandler.sendMessageDelayed(msg, 1500);
		 */
	}

	public void onLoadingMore() {
		/*
		 * Message msg = new Message(); msg.what = LOAD;
		 * mHandler.sendMessageDelayed(msg,1500);
		 */
		String url = "http://115.29.103.105/User/getRefreshDate";
		List<NameValuePair> params = new ArrayList<NameValuePair>();
		params.add(new BasicNameValuePair(Table.state, "1"));
		params.add(new BasicNameValuePair(Table.page, page + ""));
		LoadThread loadThread = new LoadThread(url, params);
		loadThread.start();
	}

	public class RefreshThread extends Thread {
		private String mUrl;
		private List<NameValuePair> mParams;

		public RefreshThread(String url, List<NameValuePair> params) {
			// TODO Auto-generated constructor stub
			mUrl = url;
			mParams = params;
		}

		@Override
		public void run() {
			// TODO Auto-generated method stub
			String context = NetManager.getNetManager().getWebWithPost(mUrl,
					mParams);
			if (context == null) {
				Log.e("you can't get data ", ".......");

				return;
			} else {
				Log.e("context=", context);
				Message msg = mHandler.obtainMessage();
				msg.what = REFRESH;
				msg.obj = context;
				// isRefreshing = true;
				mHandler.sendMessage(msg);
			}

			super.run();
		}
	}

	public class LoadThread extends Thread {
		private String mUrl;
		private List<NameValuePair> mParams;

		public LoadThread(String url, List<NameValuePair> params) {
			// TODO Auto-generated constructor stub
			mUrl = url;
			mParams = params;
		}

		@Override
		public void run() {
			// TODO Auto-generated method stub
			String context = NetManager.getNetManager().getWebWithPost(mUrl,
					mParams);
			if (context == null) {
				Log.e("you can't get data ", ".......");
			} else {
				Log.e("context=", context);
				Message msg = mHandler.obtainMessage();
				msg.what = LOAD;
				msg.obj = context;
				// isLoading = true;
				mHandler.sendMessage(msg);
			}

			super.run();
		}
	}

	/**
	 * 
	 * @param list
	 * @param context
	 *            json数据
	 * @param state
	 *            0表示刷新状态，1表示加载状态
	 */
	void addItems(List<Item> list, String context, int state) {
		JSONArray jsonArray;
		List<Item> tempItems = new ArrayList<Item>();
		try {
			jsonArray = new JSONArray(context);
			for (int i = 0; i < jsonArray.length(); i++) {
				JSONObject j = new JSONObject(jsonArray.getString(i));
				String starTime = j.getString(Table.startTime);
				if (starTime.length() - 2 > 7) {
					starTime = starTime.substring(6, starTime.length() - 2);
					starTime = Utils.getStringTime(starTime);

				}
				String endTime = j.getString(Table.endTime);
				if (endTime.length() - 2 > 7) {
					endTime = endTime.substring(6, endTime.length() - 2);
					endTime = Utils.getStringTime(endTime);
				}

				Item item = new Item(j.getString(Table.stuId),
						j.getString(Table.name), j.getString(Table.id),
						j.getString(Table.title), j.getString(Table.content),
						j.getString(Table.money), starTime, endTime,
						j.getString(Table.starts), j.getString(Table.qq),
						j.getString(Table.phone), j.getString(Table.state),
						j.getString(Table.accepStuId),
						j.getString(Table.accepName));
				tempItems.add(item);
			}
			if (state == 0) {
				list.clear();
				list.addAll(tempItems);
			} else {
				list.addAll(tempItems);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	@Override
	public void onResume() {
		String accepName; // 接单人姓名
		// TODO Auto-generated method stub
		super.onResume();
		adapter.notifyDataSetChanged();
	}
}










